﻿using EnvDTE;
using EnvDTE80;
using Microsoft.VisualStudio.CommandBars;

namespace Blader.UI
{
    public class VsMenu
    {
        private DTE2 applicationObject;
        private AddIn addInInstance;

        public DTE2 ApplicationObject
        {
            get { return applicationObject; }
            set { applicationObject = value; }
        }

        public AddIn AddInInstance
        {
            get { return addInInstance; }
            set { addInInstance = value; }
        }

        public void SetupMenu()
        {
            object[] contextGuids = new object[] { };
            Commands2 commands = (Commands2)applicationObject.Commands;
            CommandBar menuBarCommandBar = ((CommandBars)applicationObject.CommandBars)["MenuBar"];
            CommandBarControl commandBarControl = null;
            CommandBar codeCommandBar = null;

            //set up menus
            try
            {
                commandBarControl = menuBarCommandBar.Controls["Blade"];
                if (commandBarControl != null)
                    return;
                codeCommandBar = ((CommandBars)applicationObject.CommandBars)["Code Window"];
            }
            catch (System.ArgumentException)
            {
                commands.AddCommandBar("Blade(&B)", vsCommandBarType.vsCommandBarTypeMenu, menuBarCommandBar, 6);
                commandBarControl = menuBarCommandBar.Controls["Blade"];
            }

            //set up commands
            foreach (MenuItem menuItem in MenuItemCollection.MenuItems)
            {
                Command command = commands.AddNamedCommand2(addInInstance, menuItem.Name, menuItem.Text, menuItem.Desc, true, 59, ref contextGuids, (int)vsCommandStatus.vsCommandStatusSupported + (int)vsCommandStatus.vsCommandStatusEnabled, (int)vsCommandStyle.vsCommandStylePictAndText, vsCommandControlType.vsCommandControlTypeButton);
                //add to menu
                if ((command != null) && (commandBarControl != null))
                {
                    command.AddControl(((CommandBarPopup)commandBarControl).CommandBar, 1);
                }
                // add to context
                if (command != null && codeCommandBar != null)
                {
                    command.AddControl(codeCommandBar, 1);
                }
            }
        }

        public void QueryStatus(string commandName, vsCommandStatusTextWanted neededText, ref vsCommandStatus status)
        {
            if (neededText == vsCommandStatusTextWanted.vsCommandStatusTextWantedNone)
            {
                MenuItem menuItem = MenuItemCollection.FindByName(commandName);
                if (menuItem != null)
                {
                    status = vsCommandStatus.vsCommandStatusSupported | vsCommandStatus.vsCommandStatusEnabled;
                    return;
                }
            }
        }
    }
}
